<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="institutionName">
              <el-input v-model="searchForm.institutionName" clearable placeholder="医检名称"></el-input>
            </el-form-item>
            <el-form-item prop="institutionCode">
              <el-input v-model="searchForm.institutionCode" clearable placeholder="医检编号"></el-input>
            </el-form-item>
            <el-form-item prop="areaIds">
              <Region :areaValues="searchForm.areaIds" :isChangeOnSelect="true"
                      @regionChange="handleRegionChange"></Region>
            </el-form-item>
            <el-form-item prop="institutionType">
              <el-select v-model="searchForm.institutionType" :clearable="true" placeholder="请选择医检类型">
                <el-option v-for="item in reviewStatue" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="state">
              <el-select v-model="searchForm.state" :clearable="true" placeholder="请选择医检状态">
                <el-option v-for="item in agenciesStatue" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="onSearch">搜索</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="init" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()"
                       size="mini"> 新增
            </el-button>
            <el-button type="success" plain icon="el-icon-suitcase" v-has="permissionBatchSetBusinessMan"
                       @click="handleClickBatchSetBusinessMan()" size="mini"
            >批量设置业务员
            </el-button
            >
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <el-table :data="tableList" @selection-change="changeSelect" :fit="true">
        <!--<el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="institutionImageUrl" label="机构头像" width="100">
          <template slot-scope="scope">
            <img :src="scope.row.institutionImageUrl" class="photo"/>
          </template>
        </el-table-column>-->
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column prop="institutionCode" label="医检编号" width="100" align="center"></el-table-column>
        <el-table-column prop="institutionName" label="医检名称" width="180"></el-table-column>
        <el-table-column label="医检类型" width="100">
          <template slot-scope="scope">
            <span>
              <el-tag :type="formatInsTypes(scope.row.institutionType)" size="mini" effect="plain">
                {{ formatInsType(scope.row.institutionType) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="contactsName" label="联系人" width="100"></el-table-column>
        <el-table-column prop="contactsTitle" label="联系人职称" width="100"></el-table-column>
        <el-table-column prop="contactsTel" label="联系人手机" width="150"></el-table-column>
        <el-table-column label="所在地区" :filter-multiple="true">
          <template slot-scope="scope">
            <span>{{ scope.row.provinceName }}</span
            ><span>{{ scope.row.cityName }}</span
          ><span>{{ scope.row.areaName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="医检状态" align="center" width="100">
          <template slot-scope="scope">
            <span>
              <el-tag :type="formatStates(scope.row.state)" size="mini" effect="dark">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="创建时间"></el-table-column>
        <el-table-column label="操作" align="left" width="150">
          <template slot-scope="scope">
            <el-row>
              <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑
                  </el-dropdown-item>
                  <el-dropdown-item v-has="permissionEdit" @click.native="handleClickHideHospital(scope.row)">预约隐藏
                  </el-dropdown-item>
                  <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">
                    {{ scope.row.state == 0 ? '启用' : '禁用' }}
                  </el-dropdown-item>
                  <el-dropdown-item v-has="permissionDelete" v-if="scope.row.state == 0"
                                    @click.native="handleClickDelete(scope.row)">删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <!--设置业务员组件 -->
    <BatchSetBusinessMan ref="batchSetBusinessMan" :relation-type="1"></BatchSetBusinessMan>

    <el-dialog title="设置预约单隐藏医院" :visible.sync="hideHospitalDialogShow" :center="isCenter" width="400px">
      <el-form :model="hideHospitalForm" ref="hideHospitalFormRef">
        <el-form-item label="医检名称" label-width="100px">
          <span>{{ hideHospitalForm.institutionSelName }}</span>
        </el-form-item>
        <el-form-item label="医院名称" prop="hospitalSelIds" label-width="100px">
          <el-select v-model="hideHospitalForm.hospitalSelIds" clearable multiple reserve-keyword
                     placeholder="请选择医院">
            <el-option v-for="item in hospitalNameList" :key="item.hospitalId" :label="item.hospitalName"
                       :value="item.hospitalId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item align="center" style="margin-top: 50px">
          <el-button type="primary" @click="sureHideHospitalClick">保 存</el-button>
          <el-button @click="cancelHideHospitalClick">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import InstitutionApi from '@/api/institution/institution';
import HospitalApi from '@/api/institution/hospital';
import Region from '@/components/Region';
import BatchSetBusinessMan from '@/components/BatchSetBusinessMan';

export default {
  name: 'InstituManagement', // 缓存当前页面，需要给当前页面命名，并且在路由meta加上cache:true
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      tableList: [],
      selectIds: [],
      hospitalNameList: [],
      hideHospitalForm: {
        institutionId: '',
        hospitalSelIds: [],
        institutionSelName: '',
      },
      hideHospitalDialogShow: false,
      isCenter: true,

      page: {
        pageNo: 1,
        pageSize: 20,
        pageTotal: 0,
      },
      searchForm: {
        institutionName: '',
        institutionCode: '',
        institutionType: '',
        provinceId: '',
        cityId: '',
        areaId: '',
        areaIds: [],
        state: '',
      },
      reviewStatue: [
        {label: '医检机构', value: 1},
        {label: '三甲机构', value: 2},
      ],
      agenciesStatue: [
        {label: '禁用', value: '0'},
        {label: '启用', value: '1'},
        /* { label: "待审核", value:"2"}*/
      ],
      permissionAdd: 'SYSTEM_MANAGER_INSTITU_INSTITUTION_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_INSTITU_INSTITUTION_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_INSTITU_INSTITUTION_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_INSTITU_INSTITUTION_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_INSTITU_INSTITUTION_LIST_DELETE',
      permissionBatchSetBusinessMan: 'SYSTEM_MANAGER_INSTITU_INSTITUTION_LIST_BATCH_SET_BUSINESS_MAN',
    };
  },
  components: {
    BatchSetBusinessMan,
    Region,
  },
  created() {
    //console.log("---------------created---------------")
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  watch: {
    //to去哪，from从哪来
    $route(to, from) {
      if (from.path == '/institu/instituEdit' || from.path == '/institu/instituAdd') {
        this.listTable();
      }
    },
  },
  //activated,deactivated这两个生命周期函数一定是要在使用了keep-alive组件后才会有的，否则则不存在
  activated() {
    if (this.$route.meta.keepAlive) {
      this.init();
    }
    // this.init();
    //console.log(this.searchForm)
    // 从新增、修改、详情页跳转回来后，再刷新一下当前页，如果不想刷新，就去掉这行
    //console.log("---------------activated---------------")
    //this.init();
    if (this.$route.params.institutionId) {
      let institutionItem = this.tableList.filter((item) => {
        return item.institutionId == this.$route.params.institutionId;
      });
      let index = this.tableList.indexOf(institutionItem[0]);
      for (let item in this.tableList[index]) {
        if (this.$route.params[item]) {
          this.tableList[index][item] = this.$route.params[item];
        }
      }
    }
  },
  // deactivated(){
  //   // 当路由发生变化，都会执行
  //   console.log("---------------deactivated---------------")
  // },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      let _this = this;
      /*本地存储查询条件，下次进来就可以保留查询条件去查询，但使用keeperAlive更方便
      let param = getLocalStorage(stn.INSTITU_MANAGEMENT_PARAM)
      if (!_this.$Utils.isUndefined(param)){
        let paramObj = JSON.parse(param);
        _this.$Utils.bindingBean(_this.searchForm,paramObj)
        _this.$Utils.bindingBean(_this.page,paramObj)
      }*/
      _this.listTable();
      //_this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    formatInsType(cellValue) {
      if (cellValue == 1) {
        return '医检机构';
      } else if (cellValue == 2) {
        return '三甲机构';
      }
    },
    formatInsTypes(cellValue) {
      if (cellValue == 1) {
        return '';
      } else if (cellValue == 2) {
        return 'warning';
      }
    },
    formatState(cellValue) {
      if (cellValue == -1) {
        return '删除';
      } else if (cellValue == 0) {
        return '禁用';
      } else if (cellValue == 1) {
        return '启用';
      } else if (cellValue == 2) {
        return '待审核';
      }
    },
    formatStates(cellValue) {
      if (cellValue == -1) {
        return 'danger';
      } else if (cellValue == 0) {
        return 'info';
      } else if (cellValue == 1) {
        return 'success';
      } else if (cellValue == 2) {
        return '';
      }
    },
    formatDateTime(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, 'yyyy-MM-dd hh:mm:ss');
    },
    changeSelect(val) {
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        this.selectIds.push(val[i].institutionId);
      }
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listTable();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listTable();
    },
    handleClickAdd() {
      this.$router.push('/institu/instituAdd');
    },
    handleClickEditor(row) {
      this.$router.push({path: '/institu/instituEdit', query: {id: row.institutionId}});
    },
    handleClickBatchSetBusinessMan() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        _this.$refs.batchSetBusinessMan.handleCreate(this.selectIds);
      } else {
        _this.$notify.error({
          title: message.TITLE_ERROR,
          message: '请至少选择一条记录！',
        });
      }
    },
    handleClickHideHospital(row) {
      HospitalApi.getHospitalByInstitution({institutionId: row.institutionId})
        .then((res) => {
          this.hospitalNameList = res.data;
        })
        .catch((error) => {
          console.error(error);
        });
      //this.$refs.hideHospitalFormRef.resetFields()
      this.hideHospitalForm.hospitalSelIds = [];
      this.hideHospitalForm.institutionId = row.institutionId;
      this.hideHospitalForm.institutionSelName = row.institutionName;
      if (row.hideHospital) {
        this.hideHospitalForm.hospitalSelIds = row.hideHospital.split(',').map(Number);
      }
      this.hideHospitalDialogShow = true;
    },
    sureHideHospitalClick() {
      if (this.hideHospitalForm.hospitalSelIds.length < 1) {
        this.$message.error('请选择医院');
      }
      let data = {
        institutionId: this.hideHospitalForm.institutionId,
        hideHospital: this.hideHospitalForm.hospitalSelIds.toString(),
      };
      InstitutionApi.editInstitution(data).then((data) => {
        this.hideHospitalDialogShow = false;
        this.$Utils.notifySuccess();
        this.listTable();
      });
    },
    cancelHideHospitalClick() {
      this.hideHospitalDialogShow = false;
    },

    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        let deleteFormData = {
          institutionId: row.institutionId,
          state: -1,
        };
        InstitutionApi.deleteInstitution(deleteFormData).then((res) => {
          this.listTable();
          this.$Utils.notifySuccess();
        });
      });
    },
    handleClickDetail(row) {
      this.$router.push({path: '/institu/instituDetail', query: {id: row.institutionId}});
    },
    handleIsDisable(row) {
      let currentState = row.state == 0 ? 1 : 0;
      this.$confirm(currentState ? '是否启用？' : '是否禁用', message.TITLE_PROMPT, {}).then(() => {
        let disableFormData = {
          institutionId: row.institutionId,
          state: currentState,
        };
        InstitutionApi.deleteInstitution(disableFormData).then((res) => {
          row.state = currentState;
          this.$Utils.notifySuccess();
        });
      });
    },
    handleRegionChange(val) {
      this.searchForm.provinceId = val.provinceId;
      this.searchForm.cityId = val.cityId;
      this.searchForm.areaId = val.areaId;
      this.searchForm.areaIds = [val.provinceId, val.cityId, val.areaId];
    },
    /*handleAudit(row){
      this.$router.push({path: "/user/InstituAudit", query: {id: row.institutionId}})
    },*/
    listTable() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        institutionName: this.searchForm.institutionName,
        institutionCode: this.searchForm.institutionCode,
        institutionType: this.searchForm.institutionType,
        provinceId: this.searchForm.provinceId,
        cityId: this.searchForm.cityId,
        areaId: this.searchForm.areaId,
        state: this.searchForm.state,
      };
      //setLocalStorage(stn.INSTITU_MANAGEMENT_PARAM,data)
      InstitutionApi.listInstitution(data)
        .then((res) => {
          this.tableList = res.data.list;
          this.page.pageTotal = res.data.total;
        })
        .catch((error) => {
          console.error(error);
        });
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.searchForm.provinceId = '';
      this.searchForm.cityId = '';
      this.searchForm.areaId = '';
      this.onSearch();
    },
  },
};
</script>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
